const model = require('../model')
const User = model.getModel('user')
const jwtKoa  = require('koa-jwt')

const {
  successResp,
  errorResp
} = require('../utils')
const utils = require('utility')
const jwt = require('jsonwebtoken');

const _filter = {
  'pwd':0,
  '__v':0
}



/* jwt密钥 */
const secret = 'jwt_secret'



function md5Pwd(pwd) {
  const salt = 'sldfkjlsdjflkjwolerjoiwerh98797!'
  return utils.md5(utils.md5(pwd + salt))
}


/* 通过token获取JWT的payload部分 */
function getJWTPayload(token) {
  // 验证并解析JWT
  return jwt.verify(token.split(' ')[1], secret);
}




class UserController {
  // 用户信息
  async info(ctx) {
     // 前端访问时会附带token在请求头
    let payload = getJWTPayload(ctx.headers.authorization)
    const userid =payload.data._id;
    let res = await User.findOne({
      _id:userid
    },_filter)
    if(res){
      return ctx.body = successResp(res)
    }
  }
  // 注册
  async register(ctx) {
    const {
      user,
      pwd
    } = ctx.request.body
    console.log(user, pwd)
    let username = await User.findOne({
      user
    })
    if (username) {
      return ctx.body = errorResp('用户名已存在')
    }
    const UserModel = new User({
      user,
      pwd:md5Pwd(pwd)
    })
    let newUser = await UserModel.save()
    let name = newUser.user
    return ctx.body = successResp({name},'用户名创建成功')
  }
  // 登陆
  async login(ctx){
    const {pwd,user} = ctx.request.body
    const username = await User.findOne({
      user,
      pwd:md5Pwd(pwd)
    },_filter)
    if(!username){
      return ctx.body = errorResp('用户名或密码错误')
    }


    const token=jwt.sign({
      data: username,
      // 设置 token 过期时间
      exp: Math.floor(Date.now() / 1000) + (60 * 60), // 60 seconds * 60 minutes = 1 hour
    }, secret)
    return ctx.body= successResp(token,"登陆成功")
  }
}


module.exports = new UserController()